<?php

include('../../include/functions.inc.php');
if (!isEmpty(getParam('operation'))) {
    switch (getParam('operation')) {
        case 'cargos':
            listCargos();
            break;
        case 'cargos1':
            listCargos1();
            break;
        case 'save':
            stepA($db, $user);
            break;
        case 'pay':
            stepB($db, $user);
            break;
        case 'new':
            preLoad($db, $user);
            break;
        case 'p':
            printInvoice($db);
            break;
    }
}

function printInvoice($db) {
    $invoice = unserialize($_SESSION["invoice"]);
    $numero = $invoice["head"]["NUMERO"];
    $serie = $invoice["serie"];
    header("Location: ../invoices/format.php?SERIE=$serie&NUMERO=$numero");
}

function listCargos() {
    header('Location: ../items/list.php');
}

function listCargos1() {
    header('Location: ../cargos/list.php');
}

function getNoFact($db, $entity) {
    $f = $db->query_select("cllg_factura_serie", "STATUS=1 AND FK_ENTITY=" . $entity);
    if (count($f) > 0) {
        return $f[0];
    }
    return null;
}

function getNextFactura($db, $serie, $entity) {
    $f = $db->queryToArray("select max(NUMERO) No FROM cllg_factura WHERE FK_ENTITY=" . $entity .
            " AND SERIE=" . sqlValue($serie, "text"));

    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 0;
    }
}

function getNextIDFactura($db) {
    $f = $db->queryToArray("select max(ID) as No FROM cllg_factura");
    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 1;
    }
}

function stepA($db, $user) {
    $next = getNextFactura($db, getParam("SERIE"), $user->entity);
    $next++;
    $serie = getParam("SERIE");
    $student = getParam("STUDENT");
    $sinTasaCambio = getParam("TASA", 0);
    $strFechaFactura = getParam("FECHAPAGO");
    $sinMora = 0;
    $sinDolares = 0;

    $factura = array(
        "NUMERO" => $next,
        "SERIE" => sqlValue($serie, "text"),
        "FECHA" => sqlValue($strFechaFactura, "date"),
        "TOTAL" => sqlValue(getParam("TOTAL"), "double"),
        "NOMBRE" => sqlValue(getParam("NOMBRE"), "text"),
        "DIRECCION" => sqlValue(getParam("DIR"), "text"),
        "NIT" => sqlValue(getParam("NIT"), "text"),
        "IVA" => sqlValue(getParam("IVA"), "double"),
        "TIPO_PAGO" => sqlValue(getParam("TPAGO"), "text"),
        "SUBTOTAL" => sqlValue(getParam("TOTAL") - getParam("IVA"), "double"),
        "NO_BOLETA" => sqlValue(getParam("BOLETA"), "text"),
        "FK_ENTITY" => $user->entity,
        "STATUS" => sqlValue(getParam("STATUS"), "int"),
        "FK_STUDENT" => sqlValue($student, "int"),
        'DOLARES' => 0,
        'TASA_CAMBIO' => 0);

    $cargos = json_decode(stripslashes(getParam('json')), TRUE);
    $detalle = array();
    $cargo = array();
    foreach ($cargos as $c) {
        $det = array("DESCRIPCION" => sqlValue($c["DESCRIPCION"], "text"),
            "CANTIDAD" => $c["CANTIDAD"],
            "SUBTOTAL" => $c["SUBTOTAL"],
            "FK_FACTURA" => 0);
        $detalle[] = $det;
        //$db->query_insert("cllg_factura_detalle",$det);
    }

    $account = $db->queryToArray("select ID FROM cllg_account WHERE FK_STUDENT = " . $student . "  AND STATUS = 1 ");

    $strDate = date("y-m-d");
    $cargos1 = json_decode(stripslashes(getParam('json1')), TRUE);
    foreach ($cargos1 as $c) {
        $sinTot = $c["TOT"];
        $sinAbono = $c["ABONO"];
        $sinPenal = $c["PENAL"];
        $intMoneda = $c["MONEDA"];
        $sinMontoQ = 0;
        $sinMontoD = 0;
        if ($intMoneda == 2) {
            $sinMontoQ = ($sinAbono - $sinPenal) * $sinTasaCambio;
            $sinMontoD = ($sinAbono - $sinPenal);
            $sinDolares += $sinMontoD;
        } else {
            $sinMontoQ = ($sinAbono - $sinPenal);
        }
        $det = array(
            "DESCRIPCION" => sqlValue($c["DESCRIPTION"], "text"),
            "CANTIDAD" => 1,
            "SUBTOTAL" => $sinMontoQ,
            "SUBTOTAL_DOLARES" => $sinMontoD,
            "FK_FACTURA" => 0
        );
        $detalle[] = $det;

        //Si hay mora 
        if ($sinPenal > 0) {
            $sinMontoQ = 0;
            $sinMontoD = 0;
            if ($intMoneda == 2) {
                $sinMontoQ = $sinPenal * $sinTasaCambio;
                $sinMontoD = $sinPenal;
                $sinDolares += $sinMontoD;
            } else {
                $sinMontoQ = $sinPenal;
            }
            $det = array(
                "DESCRIPCION" => sqlValue('Pago Mora', "text"),
                "CANTIDAD" => 1,
                "SUBTOTAL" => $sinMontoQ,
                "SUBTOTAL_DOLARES" => $sinMontoD,
                "FK_FACTURA" => 0
            );
            $detalle[] = $det;
            $sinMora += $sinMontoQ;
        }

        $car = array(
            'ID' => $c["ID"],
            'TOTAL' => sqlValue($sinTot, 'double'),
            'TOTAL_PENDIENTE' => sqlValue(($sinTot - $sinAbono), 'double'),
            'FK_ACCOUNT' => sqlValue($account[0]['ID'], 'int'),
            'PENALTY' => sqlValue($sinPenal, "float"),
            "DESCRIPTION" => sqlValue($c["DESCRIPTION"], "text"),
            'CREATED' => sqlValue($strFechaFactura, 'date'),
            'CREATED_BY' => sqlValue($user->name, 'text'),
            "TOTAL_ABONO" => sqlValue($sinAbono, 'float')
        );
        //Si cancela por completo el cargo
        if ($sinAbono == $sinTot) {
            $car['DATE_PAYED'] = sqlValue($strFechaFactura, "date");
        }
        $cargo[] = $car;
    }

    if ($sinMora > 0) {
        $factura['MORA'] = $sinMora;
    }
    if ($sinDolares > 0) {
        $factura['DOLARES'] = $sinDolares;
        $factura['TASA_CAMBIO'] = $sinTasaCambio;
    }
    $invoice = array("head" => $factura, "detail" => $detalle, "cargo" => $cargo);
    $invoice["serie"] = $serie;
    $invoice["total"] = getParam("TOTAL");
    $_SESSION["invoice"] = serialize($invoice);

    
    if( $factura["STATUS"] == 2 ) {
        saveAllData($db, $user);
    }
    else {
        header('Location: ../payments/wayspay.php?urlData=../facturas/data.php');
    }
    
}

function stepB($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);
    $head = $invoice["head"];

    $head["EFECTIVO"] = sqlValue(getParam("EFECTIVO"), "double");
    $head["TARJETA"] = sqlValue(getParam("TARJETA"), "double");
    $head["DEPOSITO"] = sqlValue(getParam("DEPOSITO"), "double");
    $head["NO_BOLETA"] = sqlValue(getParam("NO_BOLETA"), "double");
    $head["CHEQUE"] = sqlValue(getParam("CHEQUE"), "double");

    if (doubleval(getParam("CHEQUE") > 0)) {
        $invoice["chk"] = array("NUMERO" => getParam("NOCHEKE"),
            "BANCO" => getParam("BANCO"),
            "MONTO" => getParam("CHEQUE"),
            "FECHACOBRO" => getParam("FECHACOBRO"),
            "CONCEPTO" => getParam("CONCEPTO"));
    }
    $invoice["head"] = $head;
    $_SESSION["invoice"] = serialize($invoice);

    saveAllData($db, $user);
}

function saveAllData($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);

    //persiste la informacion de la factura
    $head = $invoice["head"];
    $db->query_insert("cllg_factura", $head);

    $fk = getNextIDFactura($db);
    $details = $invoice["detail"];
    foreach ($details as $det) {
        $det["FK_FACTURA"] = $fk;
        $db->query_insert("cllg_factura_detalle", $det);
    }

    $arrCargosAbonos = $invoice["cargo"];
    foreach ($arrCargosAbonos as $arrCarAbo) {

        $intCargo = $arrCarAbo['ID'];
        $car['TOTAL'] = $arrCarAbo['TOTAL'];
        $car['TOTAL_PENDIENTE'] = $arrCarAbo['TOTAL_PENDIENTE'];
        if (isset($arrCarAbo['DATE_PAYED'])) {
            $car['DATE_PAYED'] = $arrCarAbo['DATE_PAYED'];
        }
        $db->query_update('cllg_cargo', $car, "ID=" . $intCargo);


        $intCiclo = 0;
        $strQuery = "SELECT  cllg_student_assign.FK_CYCLE
                    FROM    cllg_cargo,
                            cllg_student_assign
                    WHERE   cllg_cargo.ID = {$intCargo}
                    AND     cllg_cargo.FK_STUDENT_ASSIGN = cllg_student_assign.ID";
        $db->query($strQuery);
        while ($arrFila = $db->fetch_assoc()) {
            $intCiclo = $arrFila['FK_CYCLE'];
        }
        $db->free_result($db->query_id);
        if ($intCiclo > 0) {
            $strQuery = "UPDATE cllg_college_cycle SET MONEY_IN = MONEY_IN + {$arrCarAbo['TOTAL_ABONO']} WHERE CODE = {$intCiclo} AND FK_ENTITY = " . $user->entity;
            $db->query($strQuery);
        }

        unset($arrCarAbo['ID']);
        unset($arrCarAbo['DATE_LIMIT']);
        unset($arrCarAbo['AMOUNT']);
        unset($arrCarAbo['DATE_PAYED']);
        unset($arrCarAbo['TOTAL_PENDIENTE']);
        unset($arrCarAbo['MONEDA']);
        unset($arrCarAbo['TIPO_CARGO']);
        $arrCarAbo['TOTAL'] = $arrCarAbo['TOTAL_ABONO'];
        unset($arrCarAbo['TOTAL_ABONO']);
        $db->query_insert("cllg_abono", $arrCarAbo);
        $intAbono = mysql_insert_id();

        $arrMovCargo = array();
        $arrMovCargo['FK_CARGO'] = $intCargo;
        $arrMovCargo['FK_FACTURA'] = $fk;
        $arrMovCargo['MONTO'] = $arrCarAbo['TOTAL'];
        $arrMovCargo['CREATED'] = $arrCarAbo['CREATED'];
        $arrMovCargo['CREATED_BY'] = sqlValue($user->name, 'text');
        $arrMovCargo['FK_ABONO'] = $intAbono;
        $db->query_insert("cllg_mov_cargo", $arrMovCargo);
    }

    //guarda los datos del cheque
    $cheque = $invoice["chk"];
    if ($cheque != null) {
        $cheque["FACTURA"] = $fk;
        saveCheque($db, $cheque);
    }
    $_SESSION["invoice"] = serialize($invoice);

    if( $head["STATUS"] == 1 ) { //si la factura fue pagada!
        $res = array("R" => 1, "FACTURA" => $invoice["head"]["SERIE"] . "-" . $invoice["head"]["NUMERO"],
        "SERIE" => $invoice["head"]["SERIE"],
        "NUMERO" => $invoice["head"]["NUMERO"],
        "s" => getParam("STATUS"),
        "VIEW" => "data/invoices.php");
        $_SESSION['pack'] = serialize($res);
        header('Location: ../../include/transport.php');
    }
    else { //si se dejo pendiente de pago entonces se imprime la factura
        printInvoice($db);
    }

}

function saveCheque($db, $valCk) {
    $cheque = array("NUMERO" => sqlValue($valCk["NUMERO"], "text"),
        "FECHA" => sqlValue(date("y-m-d"), "date"),
        "MONTO" => sqlValue($valCk["MONTO"], "double"),
        "BANCO" => sqlValue($valCk["BANCO"], "text"),
        "FK_FACURA" => sqlValue($valCk["FACTURA"], "int"),
        "FECHA_COBRO" => sqlValue($valCk["FECHACOBRO"], "date"));

    $db->query_insert("cllg_cheque", $cheque);
}

function preLoad($db, $user) {
    $fac = getNoFact($db, $user->entity);
    $_SESSION["factura"] = $fac;
    header('Location: index.php');
}

?>